from django.core.cache import cache
from django.db import models

from utils.models import BaseModel


# Create your models here.
class NavCategory(BaseModel):
    name = models.CharField(max_length=32, verbose_name="导航名称")
    weight = models.IntegerField(default=0, verbose_name="权重")
    external_link = models.CharField(max_length=128, null=True, blank=True, verbose_name="外链")

    class Meta:
        verbose_name = "导航分类"
        verbose_name_plural = verbose_name
        db_table = "tb_nav_category"

    def __str__(self):
        return self.name


class CourseCategory(BaseModel):
    name = models.CharField(max_length=50, verbose_name="课程分类名称")
    level = models.IntegerField(verbose_name="分类层级")
    desc = models.CharField(max_length=128, verbose_name="分类描述")
    parent = models.ForeignKey("self", null=True, blank=True, verbose_name="父级分类", on_delete=models.CASCADE)

    class Meta:
        verbose_name = "课程分类"
        verbose_name_plural = verbose_name
        db_table = "tb_course_category"

    def __str__(self):
        return self.name


class Banner(BaseModel):
    title = models.CharField(max_length=50, verbose_name="轮播标题")
    image = models.CharField(max_length=256, verbose_name="轮播图片")
    link = models.URLField(max_length=256, verbose_name="轮播链接")
    note = models.CharField(max_length=128, verbose_name="轮播说明")

    class Meta:
        verbose_name = "轮播图"
        verbose_name_plural = verbose_name
        db_table = "tb_banner"

    def __str__(self):
        return self.title

    def save(self, *args, **kwargs):
        super().save(*args, **kwargs)
        cache_key = "code_env_spaces:home:banner"
        cache.delete(cache_key)

    def delete(self, *args, **kwargs):
        super().delete(*args, **kwargs)
        cache_key = "code_env_spaces:home:banner"
        cache.delete(cache_key)
